package cn.yunhe.crm.controller;


import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.yunhe.crm.annotation.SystemLog;
import cn.yunhe.crm.dao.DeptMapper;
import cn.yunhe.crm.dao.PositionMapper;
import cn.yunhe.crm.entity.Dept;
import cn.yunhe.crm.entity.Emp;
import cn.yunhe.crm.entity.Position;
import cn.yunhe.crm.listener.SessionBindingLisenter;
import cn.yunhe.crm.service.EmpService;
import cn.yunhe.crm.service.SysLogService;

@Scope("prototype")
@Controller
public class EmpController {
	
	@Autowired
	@Qualifier("EmpService")
	private EmpService eService;
	
	public void seteService(EmpService eService) {
		this.eService = eService;
	}
	
	@Autowired
	@Qualifier("syslogService")
	private SysLogService syslogservice;
	
	public void setSyslogbiz(SysLogService syslogservice) {
		this.syslogservice = syslogservice;
	}
	
	@Autowired
	private DeptMapper dMapper;

	public void setdMapper(DeptMapper dMapper) {
		this.dMapper = dMapper;
	}
	
	@Autowired
	private PositionMapper pMapper;
	
	public void setpMapper(PositionMapper pMapper) {
		this.pMapper = pMapper;
	}
	
	/**
	 * 登录页面访问控制
	 * @return
	 */ 
	@RequestMapping("/tologin.do")
	public String tologin(){
		Subject subject=SecurityUtils.getSubject();
		if(subject.isAuthenticated()){
			return "index";
		}
		return "log";
	}

	/**
	 * 登录验证
	 * @param emp
	 * @param request
	 * @return
	 */
	@RequestMapping("login.do")
	public String login(Emp emp,HttpServletRequest request){
		//获取session
		HttpSession session=request.getSession();
		//获取用户主体
		Subject subject=SecurityUtils.getSubject();
		//对前台传过来的密码进行加密处理
		//String password=new Md5Hash(emp.getUsername(),emp.getPassword()).toString();
		//对前台传过来的数据进行处理主要是把密码转化为char数组
		UsernamePasswordToken token=new UsernamePasswordToken(emp.getUsername(),emp.getPassword());
		
		ServletContext application = session.getServletContext();
		
		try {
			//底层调用方法将提交信息和从数据库里面查出的信息进行对比，如果不匹配会抛出异常
			subject.login(token);
			//检查当前用户是否在线
			Map map=(Map) application.getAttribute("usermap");
			if(map!=null){
				HttpSession ses=(HttpSession) map.get(emp.getUsername());
				if(ses!=null&&ses.getId()!=session.getId()){
					//如果已经登录，强制前一个登录的session失效
					ses.invalidate();
				}
			}
			SessionBindingLisenter sessionLisenter=new SessionBindingLisenter(emp.getUsername(),session);
			//将监听器植入HttpSession
			session.setAttribute("listen", sessionLisenter);
			Emp e=eService.getByUserName(emp.getUsername());
			//将用户对象放入session中
			session.setAttribute("user", e);
			session.setAttribute("logintime", new Date());
			System.out.println("用户："+e.getEmpname()+"使用session"+session.getId()+"登录");
			//获取当前在线用户数量
			Map m=(Map) application.getAttribute("usermap");
			System.out.println("当前在线用户人数"+m.size());
			return "redirect:/index.do";
		} catch (AuthenticationException e) {
			e.printStackTrace();
			request.setAttribute("user", emp);
			request.setAttribute("errorMsg", "用户名或密码错误");
			return "log";
		}
	}
	
	/**
	 * 用户退出
	 * @return
	 */
	@RequestMapping("/loginout.do")
	public String loginout(HttpServletRequest request,HttpSession session){
		
		//判断session里面是否有对象来确定session是否过期
		if(session.getAttribute("user")==null){
			return "log";
		}else{
			Subject subject=SecurityUtils.getSubject();
			subject.logout();
			return "log";
		}	
	}
	

	/**
	 * 查询所有员工信息
	 * @param session
	 * @return
	 */
	@RequestMapping("empinfo.do")
	public String checkAllEmp(HttpSession session){
		List<Emp> emps=eService.checkAllEmp();
		session.removeAttribute("emps");
		session.setAttribute("emps", emps);
		return "empinfo";
	}
	
	/**
	 * 查询所有部门以及岗位信息
	 * @return
	 */
	@RequestMapping("empinfoadd.do")
	public String checkAllDeptAndPosition(HttpSession session){
		List<Dept> depts=dMapper.selectByExample(null);
		List<Position> positions=pMapper.selectByExample(null);
		session.removeAttribute("depts");
		session.setAttribute("depts", depts);
		session.removeAttribute("positions");
		session.setAttribute("positions", positions);
		return "empinfoadd";
	}
	/**
	 * 新增员工
	 * @return
	 */
	@SystemLog(des="新增员工")
	@RequestMapping("empadd.do")
	public String addEmp(Emp emp){
		int flag=eService.addEmp(emp);
		if(flag>0){
			return "redirect:/empinfo.do";
		}else{
			return "empinfoadd";
		}
	}
	/**
	 * 判断手机号唯一性
	 * @return
	 */
	@RequestMapping("phone.do")
	@ResponseBody
	public String checkEmpByPhone(String phone){
		Emp emp=eService.checkEmpByPhone(phone);
		if(emp!=null){
			return "true";
		}else{
			return "false";
		}
		
	}
	/**
	 * 员工详情
	 * @param id
	 * @param session
	 * @return
	 */
	@RequestMapping(value="empinfodetail.do")
	public String detailEmp( Integer id,HttpSession session){
		Emp emp=eService.checkEmpById(id);
		session.removeAttribute("emp");
		session.setAttribute("emp", emp);
		return "empinfodetail";	
	}
	/**
	 * 跳转至编辑员工界面
	 * @param id
	 * @param session
	 * @return
	 */
	@RequestMapping(value="empinfoupdate.do")
	public String toempinfodetail(Integer id,HttpSession session){
		Emp emp=eService.checkEmpById(id);
		List<Dept> depts=dMapper.selectByExample(null);
		List<Position> positions=pMapper.selectByExample(null);
		session.removeAttribute("depts");
		session.setAttribute("depts", depts);
		session.removeAttribute("positions");
		session.setAttribute("positions", positions);
		session.removeAttribute("emp");
		session.setAttribute("emp", emp);
		return "empinfoupdate";
	}
	
	/**
	 * 编辑员工信息
	 * @return
	 */
	@SystemLog(des="更新员工")
	@RequestMapping("empupdate.do")
	public String updateEmp(Emp emp){
		int flag=eService.updateEmp(emp);
		if(flag>0){
			return "redirect:/empinfo.do";
		}else{
			return "empinfoupdate";
		}
	}
	/**
	 * 删除员工
	 * @param id
	 * @return
	 */
	@SystemLog(des="删除员工")
	@RequestMapping(value="empinfodel.do")
	public String delEmp(Integer id){
		int flag=eService.delEmp(id);
		if(flag>0){
			return "redirect:/empinfo.do";
		}else{
			return "empinfo";
		}
	}
	/**
	 * 刷新修改密码页面
	 * @return
	 */
	@RequestMapping("/changepwd.do")
	public String changepwd(){
		return "changepwd";
	}
	/***
	 * 通过id和密码 查询是否存在此客户
	 * @param id
	 * @param password
	 * @return
	 */
	@ResponseBody
	@RequestMapping("empByIdAndPwd.do")
	public Object empByIdAndPwd(Integer id,String password){
		Emp emp= new Emp();
		emp.setId(id);
		emp.setPassword(password);
		Emp em=eService.getEmpByIdAndPwd(emp);
		Map map = new HashMap();
		if(em !=null){
			map.put("res","true");
		}else{
			map.put("res","false");
		}
		return JSONObject.toJSONString(map);
	}
	
	/**
	 * 密码修改后提交跳转到开始登陆页面
	 * @param emp
	 * @return
	 */
	@RequestMapping("/pwdEmpById.do")
	public String updatePwdById(Emp emp){
		int flag=eService.updatePwdById(emp);
		if(flag>0){
			return "redirect:main.do";
		}else
			return "redirect:changepwd.do";
	}
	
	
}
